package com.uniflow.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uniflow.entity.ThirdPartyIntegration;
import com.uniflow.mapper.ThirdPartyIntegrationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 第三方集成服务实现类
 */
@Service
public class ThirdPartyIntegrationService extends ServiceImpl<ThirdPartyIntegrationMapper, ThirdPartyIntegration> {
    
    @Autowired
    private ThirdPartyIntegrationMapper thirdPartyIntegrationMapper;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 分页查询第三方集成
     */
    public IPage<ThirdPartyIntegration> getPageList(Integer pageNum, Integer pageSize, String name,
                                                    String integrationType, String systemType, String status,
                                                    String connectionStatus, String category, Boolean enabled,
                                                    String createdBy, LocalDateTime startTime, LocalDateTime endTime,
                                                    String keyword, String tenantId) {
        Page<ThirdPartyIntegration> page = new Page<>(pageNum, pageSize);
        IPage<ThirdPartyIntegration> result = thirdPartyIntegrationMapper.selectPageList(page, name, integrationType,
                systemType, status, connectionStatus, category, enabled, createdBy, startTime, endTime, keyword, tenantId);
        
        // 丰富集成信息
        result.getRecords().forEach(this::enrichIntegrationInfo);
        
        return result;
    }
    
    /**
     * 根据ID查询第三方集成
     */
    public ThirdPartyIntegration getById(String id, String tenantId) {
        ThirdPartyIntegration integration = thirdPartyIntegrationMapper.selectById(id);
        if (integration != null && tenantId.equals(integration.getTenantId())) {
            enrichIntegrationInfo(integration);
        }
        return integration;
    }
    
    /**
     * 根据名称查询第三方集成
     */
    public List<ThirdPartyIntegration> getByName(String name, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByName(name, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据外部ID查询第三方集成
     */
    public ThirdPartyIntegration getByExternalId(String externalId, String tenantId) {
        ThirdPartyIntegration integration = thirdPartyIntegrationMapper.selectByExternalId(externalId, tenantId);
        if (integration != null) {
            enrichIntegrationInfo(integration);
        }
        return integration;
    }
    
    /**
     * 根据业务键查询第三方集成
     */
    public ThirdPartyIntegration getByBusinessKey(String businessKey, String tenantId) {
        ThirdPartyIntegration integration = thirdPartyIntegrationMapper.selectByBusinessKey(businessKey, tenantId);
        if (integration != null) {
            enrichIntegrationInfo(integration);
        }
        return integration;
    }
    
    /**
     * 根据集成类型查询第三方集成
     */
    public List<ThirdPartyIntegration> getByIntegrationType(String integrationType, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByIntegrationType(integrationType, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据系统类型查询第三方集成
     */
    public List<ThirdPartyIntegration> getBySystemType(String systemType, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectBySystemType(systemType, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据状态查询第三方集成
     */
    public List<ThirdPartyIntegration> getByStatus(String status, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByStatus(status, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据连接状态查询第三方集成
     */
    public List<ThirdPartyIntegration> getByConnectionStatus(String connectionStatus, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByConnectionStatus(connectionStatus, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据分类查询第三方集成
     */
    public List<ThirdPartyIntegration> getByCategory(String category, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByCategory(category, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 根据创建人查询第三方集成
     */
    public List<ThirdPartyIntegration> getByCreatedBy(String createdBy, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectByCreatedBy(createdBy, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询启用的第三方集成
     */
    public List<ThirdPartyIntegration> getEnabledIntegrations(String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectEnabledIntegrations(tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询可连接的第三方集成
     */
    public List<ThirdPartyIntegration> getConnectableIntegrations(String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectConnectableIntegrations(tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询自动同步的第三方集成
     */
    public List<ThirdPartyIntegration> getAutoSyncIntegrations(String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectAutoSyncIntegrations(tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询实时同步的第三方集成
     */
    public List<ThirdPartyIntegration> getRealtimeSyncIntegrations(String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectRealtimeSyncIntegrations(tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询正在同步的第三方集成
     */
    public List<ThirdPartyIntegration> getSyncingIntegrations(String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectSyncingIntegrations(tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询有依赖关系的第三方集成
     */
    public List<ThirdPartyIntegration> getDependentIntegrations(String integrationId, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectDependentIntegrations(integrationId, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 创建第三方集成
     */
    @Transactional
    public ThirdPartyIntegration createIntegration(ThirdPartyIntegration integration) {
        // 序列化JSON字段
        serializeJsonFields(integration);
        
        // 设置默认值
        if (integration.getSortOrder() == null) {
            Integer maxSortOrder = thirdPartyIntegrationMapper.selectMaxSortOrder(integration.getTenantId());
            integration.setSortOrder(maxSortOrder != null ? maxSortOrder + 1 : 1);
        }
        
        thirdPartyIntegrationMapper.insert(integration);
        
        // 反序列化JSON字段
        deserializeJsonFields(integration);
        
        return integration;
    }
    
    /**
     * 更新第三方集成
     */
    @Transactional
    public ThirdPartyIntegration updateIntegration(ThirdPartyIntegration integration) {
        // 序列化JSON字段
        serializeJsonFields(integration);
        
        thirdPartyIntegrationMapper.updateById(integration);
        
        // 反序列化JSON字段
        deserializeJsonFields(integration);
        
        return integration;
    }
    
    /**
     * 启用第三方集成
     */
    @Transactional
    public boolean enableIntegration(String id, String updatedBy, String updatedByName) {
        ThirdPartyIntegration integration = new ThirdPartyIntegration();
        integration.setId(id);
        integration.setEnabled(true);
        integration.setUpdatedBy(updatedBy);
        integration.setUpdatedByName(updatedByName);
        return thirdPartyIntegrationMapper.updateById(integration) > 0;
    }
    
    /**
     * 禁用第三方集成
     */
    @Transactional
    public boolean disableIntegration(String id, String updatedBy, String updatedByName) {
        ThirdPartyIntegration integration = new ThirdPartyIntegration();
        integration.setId(id);
        integration.setEnabled(false);
        integration.setUpdatedBy(updatedBy);
        integration.setUpdatedByName(updatedByName);
        return thirdPartyIntegrationMapper.updateById(integration) > 0;
    }
    
    /**
     * 连接第三方集成
     */
    @Transactional
    public boolean connectIntegration(String id) {
        return thirdPartyIntegrationMapper.updateConnectionStatus(id, "CONNECTED", LocalDateTime.now()) > 0;
    }
    
    /**
     * 断开第三方集成
     */
    @Transactional
    public boolean disconnectIntegration(String id) {
        return thirdPartyIntegrationMapper.updateConnectionStatus(id, "DISCONNECTED", null) > 0;
    }
    
    /**
     * 开始同步
     */
    @Transactional
    public boolean startSync(String id, String updatedBy, String updatedByName) {
        int result = thirdPartyIntegrationMapper.updateStatus(id, "SYNCING", updatedBy, updatedByName);
        if (result > 0) {
            thirdPartyIntegrationMapper.updateLastSyncTime(id, LocalDateTime.now());
        }
        return result > 0;
    }
    
    /**
     * 停止同步
     */
    @Transactional
    public boolean stopSync(String id, String updatedBy, String updatedByName) {
        return thirdPartyIntegrationMapper.updateStatus(id, "ACTIVE", updatedBy, updatedByName) > 0;
    }
    
    /**
     * 重置第三方集成
     */
    @Transactional
    public boolean resetIntegration(String id, String updatedBy, String updatedByName) {
        int result = thirdPartyIntegrationMapper.updateStatus(id, "INACTIVE", updatedBy, updatedByName);
        if (result > 0) {
            thirdPartyIntegrationMapper.updateConnectionStatus(id, "DISCONNECTED", null);
        }
        return result > 0;
    }
    
    /**
     * 复制第三方集成
     */
    @Transactional
    public ThirdPartyIntegration copyIntegration(String id, String newName, String createdBy, String createdByName, String tenantId) {
        ThirdPartyIntegration original = getById(id, tenantId);
        if (original == null) {
            return null;
        }
        
        ThirdPartyIntegration copy = new ThirdPartyIntegration();
        // 复制属性
        copy.setName(newName);
        copy.setDescription(original.getDescription() + "（复制）");
        copy.setIntegrationType(original.getIntegrationType());
        copy.setSystemType(original.getSystemType());
        copy.setSystemName(original.getSystemName());
        copy.setSystemVersion(original.getSystemVersion());
        copy.setConnectionConfigJson(original.getConnectionConfigJson());
        copy.setAuthConfigJson(original.getAuthConfigJson());
        copy.setApiConfigJson(original.getApiConfigJson());
        copy.setMappingConfigJson(original.getMappingConfigJson());
        copy.setSyncConfigJson(original.getSyncConfigJson());
        copy.setNotificationConfigJson(original.getNotificationConfigJson());
        copy.setStatus("INACTIVE");
        copy.setConnectionStatus("DISCONNECTED");
        copy.setSyncFrequency(original.getSyncFrequency());
        copy.setAutoSync(original.getAutoSync());
        copy.setBidirectionalSync(original.getBidirectionalSync());
        copy.setRealtimeSync(original.getRealtimeSync());
        copy.setPriority(original.getPriority());
        copy.setTimeout(original.getTimeout());
        copy.setRetryCount(original.getRetryCount());
        copy.setRetryInterval(original.getRetryInterval());
        copy.setBatchSize(original.getBatchSize());
        copy.setConcurrency(original.getConcurrency());
        copy.setRateLimitConfig(original.getRateLimitConfig());
        copy.setErrorHandlingStrategy(original.getErrorHandlingStrategy());
        copy.setValidationRules(original.getValidationRules());
        copy.setTransformationRules(original.getTransformationRules());
        copy.setFilterConditions(original.getFilterConditions());
        copy.setCategory(original.getCategory());
        copy.setTags(original.getTags());
        copy.setRemark(original.getRemark());
        copy.setExtendedPropertiesJson(original.getExtendedPropertiesJson());
        copy.setEnabled(false);
        copy.setTenantId(tenantId);
        copy.setCreatedBy(createdBy);
        copy.setCreatedByName(createdByName);
        
        return createIntegration(copy);
    }
    
    /**
     * 批量删除第三方集成
     */
    @Transactional
    public boolean batchDeleteIntegrations(List<String> ids) {
        return thirdPartyIntegrationMapper.deleteBatchIds(ids) > 0;
    }
    
    /**
     * 批量更新状态
     */
    @Transactional
    public boolean batchUpdateStatus(List<String> ids, String status, String updatedBy, String updatedByName) {
        return thirdPartyIntegrationMapper.batchUpdateStatus(ids, status, updatedBy, updatedByName) > 0;
    }
    
    /**
     * 批量更新优先级
     */
    @Transactional
    public boolean batchUpdatePriority(List<String> ids, Integer priority, String updatedBy, String updatedByName) {
        return thirdPartyIntegrationMapper.batchUpdatePriority(ids, priority, updatedBy, updatedByName) > 0;
    }
    
    /**
     * 批量更新分类
     */
    @Transactional
    public boolean batchUpdateCategory(List<String> ids, String category, String updatedBy, String updatedByName) {
        return thirdPartyIntegrationMapper.batchUpdateCategory(ids, category, updatedBy, updatedByName) > 0;
    }
    
    /**
     * 批量更新排序
     */
    @Transactional
    public boolean batchUpdateSortOrder(List<String> ids, Integer sortOrder, String updatedBy, String updatedByName) {
        return thirdPartyIntegrationMapper.batchUpdateSortOrder(ids, sortOrder, updatedBy, updatedByName) > 0;
    }
    
    /**
     * 检查名称是否可用
     */
    public boolean isNameAvailable(String name, String excludeId, String tenantId) {
        return thirdPartyIntegrationMapper.checkNameAvailable(name, excludeId, tenantId) == 0;
    }
    
    /**
     * 检查业务键是否可用
     */
    public boolean isBusinessKeyAvailable(String businessKey, String excludeId, String tenantId) {
        return thirdPartyIntegrationMapper.checkBusinessKeyAvailable(businessKey, excludeId, tenantId) == 0;
    }
    
    /**
     * 获取第三方集成统计信息
     */
    public Map<String, Object> getStatistics(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatistics(tenantId);
    }
    
    /**
     * 按状态统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByStatus(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByStatus(tenantId);
    }
    
    /**
     * 按集成类型统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByIntegrationType(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByIntegrationType(tenantId);
    }
    
    /**
     * 按系统类型统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsBySystemType(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsBySystemType(tenantId);
    }
    
    /**
     * 按连接状态统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByConnectionStatus(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByConnectionStatus(tenantId);
    }
    
    /**
     * 按分类统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByCategory(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByCategory(tenantId);
    }
    
    /**
     * 按创建人统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByCreatedBy(String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByCreatedBy(tenantId);
    }
    
    /**
     * 按时间统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByTime(LocalDateTime startTime, LocalDateTime endTime, String timeUnit, String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByTime(startTime, endTime, timeUnit, tenantId);
    }
    
    /**
     * 按月份统计第三方集成数量
     */
    public List<Map<String, Object>> getStatsByMonth(Integer year, String tenantId) {
        return thirdPartyIntegrationMapper.selectStatsByMonth(year, tenantId);
    }
    
    /**
     * 获取连接成功率统计
     */
    public Map<String, Object> getConnectionSuccessRateStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectConnectionSuccessRateStats(tenantId);
    }
    
    /**
     * 获取同步成功率统计
     */
    public Map<String, Object> getSyncSuccessRateStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectSyncSuccessRateStats(tenantId);
    }
    
    /**
     * 获取平均响应时间统计
     */
    public Map<String, Object> getAvgResponseTimeStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectAvgResponseTimeStats(tenantId);
    }
    
    /**
     * 获取性能统计
     */
    public Map<String, Object> getPerformanceStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectPerformanceStats(tenantId);
    }
    
    /**
     * 获取错误统计
     */
    public Map<String, Object> getErrorStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectErrorStats(tenantId);
    }
    
    /**
     * 获取今日统计
     */
    public Map<String, Object> getTodayStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectTodayStats(tenantId);
    }
    
    /**
     * 获取本周统计
     */
    public Map<String, Object> getWeeklyStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectWeeklyStats(tenantId);
    }
    
    /**
     * 获取本月统计
     */
    public Map<String, Object> getMonthlyStats(String tenantId) {
        return thirdPartyIntegrationMapper.selectMonthlyStats(tenantId);
    }
    
    /**
     * 查询分类列表
     */
    public List<String> getCategoryList(String tenantId) {
        return thirdPartyIntegrationMapper.selectCategoryList(tenantId);
    }
    
    /**
     * 查询集成类型列表
     */
    public List<String> getIntegrationTypeList(String tenantId) {
        return thirdPartyIntegrationMapper.selectIntegrationTypeList(tenantId);
    }
    
    /**
     * 查询系统类型列表
     */
    public List<String> getSystemTypeList(String tenantId) {
        return thirdPartyIntegrationMapper.selectSystemTypeList(tenantId);
    }
    
    /**
     * 查询标签列表
     */
    public List<String> getTagList(String tenantId) {
        return thirdPartyIntegrationMapper.selectTagList(tenantId);
    }
    
    /**
     * 查询相关第三方集成
     */
    public List<ThirdPartyIntegration> getRelatedIntegrations(String integrationId, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectRelatedIntegrations(integrationId, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询依赖关系
     */
    public List<Map<String, Object>> getDependencyRelations(String integrationId, String tenantId) {
        return thirdPartyIntegrationMapper.selectDependencyRelations(integrationId, tenantId);
    }
    
    /**
     * 查询子第三方集成
     */
    public List<ThirdPartyIntegration> getChildIntegrations(String parentId, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectChildIntegrations(parentId, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    /**
     * 查询父第三方集成
     */
    public ThirdPartyIntegration getParentIntegration(String childId, String tenantId) {
        ThirdPartyIntegration integration = thirdPartyIntegrationMapper.selectParentIntegration(childId, tenantId);
        if (integration != null) {
            enrichIntegrationInfo(integration);
        }
        return integration;
    }
    
    /**
     * 查询第三方集成链
     */
    public List<ThirdPartyIntegration> getIntegrationChain(String integrationId, String tenantId) {
        List<ThirdPartyIntegration> list = thirdPartyIntegrationMapper.selectIntegrationChain(integrationId, tenantId);
        list.forEach(this::enrichIntegrationInfo);
        return list;
    }
    
    // 辅助方法
    
    /**
     * 序列化JSON字段
     */
    private void serializeJsonFields(ThirdPartyIntegration integration) {
        integration.serializeConnectionConfig();
        integration.serializeAuthConfig();
        integration.serializeApiConfig();
        integration.serializeMappingConfig();
        integration.serializeSyncConfig();
        integration.serializeNotificationConfig();
        integration.serializeExtendedProperties();
    }
    
    /**
     * 反序列化JSON字段
     */
    private void deserializeJsonFields(ThirdPartyIntegration integration) {
        integration.deserializeConnectionConfig();
        integration.deserializeAuthConfig();
        integration.deserializeApiConfig();
        integration.deserializeMappingConfig();
        integration.deserializeSyncConfig();
        integration.deserializeNotificationConfig();
        integration.deserializeExtendedProperties();
        integration.parseTags();
    }
    
    /**
     * 丰富集成信息
     */
    private void enrichIntegrationInfo(ThirdPartyIntegration integration) {
        if (integration == null) return;
        
        // 反序列化JSON字段
        deserializeJsonFields(integration);
        
        // 设置状态描述
        integration.setConnectionStatusDesc(integration.getConnectionStatusDescription());
        
        // 设置下次同步时间描述
        if (integration.isAutoSync() && StringUtils.hasText(integration.getSyncFrequency())) {
            integration.setNextSyncTimeDesc("根据频率：" + integration.getSyncFrequency());
        } else {
            integration.setNextSyncTimeDesc("手动同步");
        }
        
        // 设置是否可连接
        integration.setConnectable(integration.isEnabled() && !integration.isSyncing());
    }
}